package com.scujj.cs6.client;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.scujj.cs6.constant.BaiduWeatherConstant;
import com.scujj.cs6.model.dto.BaiduWeatherApiDTO;
import org.springframework.web.util.UriUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.net.URLConnection;

public class BaiduWeatherApiClient {
    private final String ak;

    private final String url;

    public BaiduWeatherApiClient(String accessKey, String weatherApiUrl) {
        this.ak = accessKey;
        this.url = weatherApiUrl;
    }

    /**
     * 默认ak
     * 选择了ak，使用IP白名单校验：
     * 根据您选择的AK已为您生成调用代码
     * 检测到您当前的ak设置了IP白名单校验
     * 您的IP白名单中的IP非公网IP，请设置为公网IP，否则将请求失败
     * 请在IP地址为xxxxxxx的计算发起请求，否则将请求失败
     */
    private String requestGetAK(String districtId , String dataType) throws Exception {
        String strUrl = url + "/?";

        BaiduWeatherApiDTO baiduWeatherApiDTO = new BaiduWeatherApiDTO();
        baiduWeatherApiDTO.setAk(this.ak);
        baiduWeatherApiDTO.setDistrictId(districtId);
        baiduWeatherApiDTO.setDataType(dataType);

        final StringBuilder queryString = new StringBuilder();
        queryString.append(strUrl);
        Class<?> clazz = baiduWeatherApiDTO.getClass();
        for (Field declaredField : clazz.getDeclaredFields()) {
            String key = declaredField.getAnnotation(JsonProperty.class).value();
            declaredField.setAccessible(true);
            queryString.append(key).append("=");
            queryString.append(UriUtils.encode((String) declaredField.get(baiduWeatherApiDTO), "UTF-8")).append("&");
        }

        if (!queryString.isEmpty()) {
            queryString.deleteCharAt(queryString.length() - 1);
        }

        java.net.URL url = new java.net.URL(queryString.toString());

        URLConnection httpConnection = url.openConnection();
        httpConnection.connect();

        InputStreamReader isr = new InputStreamReader(httpConnection.getInputStream());
        BufferedReader reader = new BufferedReader(isr);
        StringBuilder buffer = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        reader.close();
        isr.close();
        return buffer.toString();
    }

    /**
     * 获取天气所有信息
     * @param districtCode 行政区代码
     * @return {@link String}
     */
    public String fetchAll(String districtCode) throws Exception {
        return requestGetAK(districtCode , BaiduWeatherConstant.ALL);
    }


    /**
     * 获取天气实况
     * @param districtCode 行政区代码
     * @return {@link String}
     */
    public String fetchNow(String districtCode) throws Exception {
        return requestGetAK(districtCode , BaiduWeatherConstant.NOW);
    }



    /**
     * 获取天气未来预报
     * @param districtCode 行政区代码
     * @return {@link String}
     */
    public String fetchForecasts(String districtCode) throws Exception {
        return requestGetAK(districtCode , BaiduWeatherConstant.FORECASTS);
    }
}
